<template>
  <div class="base-map-resource-content">
    <div class="query-content">
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline backend-form"
      >
        <el-form-item label="部门名称">
          <el-input v-model="formInline.deptName" @change="onSubmit" />
        </el-form-item>
        <!--        <el-form-item>-->
        <!--          <el-button type="primary" class="queryButton" @click="onSubmit"-->
        <!--            >查询</el-button-->
        <!--          >-->
        <!--          <el-button type="primary" class="resetButton" @click="resetField"-->
        <!--            >重置</el-button-->
        <!--          >-->
        <!--        </el-form-item>-->
        <el-form-item class="backend-button">
          <el-button
            class="addButton"
            type="primary"
            @click="handleAddDept"
            v-if="currentUser?.hasPermission('bmgladd')"
          >
            <!--        <el-icon>-->
            <!--          <Plus />-->
            <!--        </el-icon>-->
            <i class="icon el-icon-plus"></i>
            {{ currentUser?.getButtonName('bmgladd') }}
          </el-button>
          <el-button
            :loading="exportLoading"
            class="addButton"
            type="primary"
            @click="handleExport"
            v-if="currentUser?.hasPermission('bmglexport')"
          >
            <i class="icon el-icon-download"></i>
            {{ currentUser?.getButtonName('bmglexport') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-content">
      <div class="table" v-loading="tableShow">
        <el-table
          :data="tableData"
          v-if="!tableShow"
          row-key="pkid"
          height="100%"
          :load="load"
          lazy
          stripe
          style="width: 100%"
        >
          <el-table-column label="部门名称">
            <template #header>
              <div>
                <span class="el-header--level-0" v-show="maxLevel <= 0"
                  >市级名称</span
                >
                <span
                  :class="
                    maxLevel === 5 ? 'el-header--level-0' : 'el-header--level-5'
                  "
                  v-show="maxLevel == 5 || maxLevel == 0"
                  >片区名称</span
                >
                <span
                  :class="
                    maxLevel === 1 ? 'el-header--level-0' : 'el-header--level-1'
                  "
                  v-show="maxLevel <= 1"
                  >区县名称</span
                >
                <span
                  :class="
                    maxLevel === 2 ? 'el-header--level-0' : 'el-header--level-2'
                  "
                  v-show="maxLevel <= 2"
                  >街道名称</span
                >
                <span
                  :class="
                    maxLevel === 3
                      ? 'el-header--level-0'
                      : maxLevel === 2
                      ? 'el-header--level-special'
                      : 'el-header--level-3'
                  "
                  >社区名称</span
                >
              </div>
            </template>
            <template #default="scope">
              <span class="areaName">
                {{ scope.row.areaName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updateTime" width="240" />
          <el-table-column label="操作" width="220">
            <template #default="scope">
              <el-button
                text
                type="text"
                style="padding: 0"
                @click="handleEditClick(scope.row)"
                v-if="
                  scope.row.pkid !== '-1' &&
                  currentUser?.hasPermission('bmgledit')
                "
              >
                {{ currentUser?.getButtonName('bmgledit') }}
              </el-button>
              <el-popconfirm
                width="160px"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon-color="#626AEF"
                @confirm="handleDeleteClick(scope.row)"
                title="确认删除该部门？"
              >
                <template #reference>
                  <el-button
                    text
                    type="text"
                    style="color: #fa3434; margin-left: 12px; padding: 0"
                    v-if="
                      scope.row.pkid !== '-1' &&
                      currentUser?.hasPermission('bmgldelete')
                    "
                    >{{
                      currentUser?.getButtonName('bmgldelete')
                    }}</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination background layout="slot" :total="total">
        <template #default> 共{{ total }}个部门 </template>
      </el-pagination>
    </div>
    <add-dept-dialog
      :dept-info="deptInfo"
      :visible="dialogVisible"
      :dept-role-dict="allDeptData"
      :all-dept-dict="deptData"
      @updateDept="handleDeptUpdate"
      @closeDialog="handleDialogClose"
    >
    </add-dept-dialog>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
// import { Plus } from '@element-plus/icons-vue'

function deepClone(obj: any) {
  // 如果是基本类型直接返回
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

  // 创建一个新的空对象或数组，用于存储深拷贝后的数据
  const clone = Array.isArray(obj) ? [] : {}

  // 遍历原对象的属性
  for (let key in obj) {
    // 如果属性是对象，则递归调用深拷贝函数
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      clone[key] = deepClone(obj[key])
    }
  }

  return clone
}

import AddDeptDialog from '@/views/backend-management/components/dept/components/addDeptDialog.vue'
import {
  deleteDept,
  deptExport,
  queryDeptList,
} from '@/api/back-management/dept'
import type { deptQueryParams } from '@/api/back-management/dept/interface'
import type { DivisionData } from '@/utils/type'
import { Message as ElMessage } from 'element-ui'
// import { useCurrentUserStore } from '@/stores/current-user'
import { PERMISSIONS } from '@/common/user'
import { downloadFileWithBlob } from '@/utils/download'

const vm = getCurrentInstance()
const store = vm.proxy.$store

const currentUser = store.state.user.currentUser

// const { currentUser } = useCurrentUserStore()

const tableShow = ref(false)

const dialogVisible = ref(false)

const formInline = reactive<deptQueryParams>({
  pageIndex: 1,
  pageSize: 11,
  deptName: '',
  districtFlag: 'true',
})
const tableData = ref<DivisionData[]>([])
const total = ref(0)
const maxLevel = ref(0)

const deptData = ref<DivisionData[]>([])

const parentDeptData = ref<DivisionData[]>([])

const deptInfo = reactive<Partial<DivisionData>>({})

const findItemFromTree = (
  pkid: string,
  treeArray: DivisionData[]
): DivisionData | null => {
  for (let i = 0; i < treeArray.length; i++) {
    const item = treeArray[i]

    // Check if the current item object has the pkid
    if (item.pkid === pkid) {
      return item // Found the item with the pkid
    }

    // If the item has children, recursively search through them
    if (item.children && item.children.length > 0) {
      const foundItem = findItemFromTree(pkid, item.children)
      if (foundItem) {
        return foundItem // Found the item with the pkid in children
      }
    }
  }

  // The pkid was not found in the tree array
  return null
}

const load = (row: any, treeNode: unknown, resolve: (date: any) => void) => {
  const item = findItemFromTree(row.pkid, deptData.value!)
  if (item) {
    const res = item.children?.map((val) => {
      const result = {
        pkid: val.pkid,
        areaCode: val.areaCode,
        areaName: val.areaName,
        parentName: item.areaName,
        parentCode: item.pkid,
        level: val.level,
        updateTime: val.updateTime,
        longitude: val.longitude,
        latitude: val.latitude,
        hasChildren: false,
        children: [],
        status: val.status,
      }
      if (val.children && val.children.length) {
        result.hasChildren = true
      }
      return result
    })
    resolve(res)
  } else {
    resolve([])
  }
}

const convertChildrenToEmptyArray = (
  treeArray: DivisionData[]
): DivisionData[] => {
  const newTreeArray: DivisionData[] = []
  treeArray.forEach((city) => {
    city.children?.forEach((region) => {
      region.children?.forEach((street) => {
        street.children = []
      })
    })
    newTreeArray.push(city)
  })
  return newTreeArray
}

const countParentsAndChildren = (arr: DivisionData) => {
  // console.log(arr);
  let count = 0

  function traverse(element: DivisionData) {
    // console.log(element);
    count++ // count the current element as a parent or child

    if (Array.isArray(element.children)) {
      for (let i = 0; i < element.children.length; i++) {
        traverse(element.children[i])
      }
    }
  }

  traverse(arr)
  return count
}

let init = false

const allDeptData = ref([])

const getDeptList = () => {
  tableShow.value = true
  queryDeptList(formInline)
    .then((res) => {
      tableShow.value = false
      if (res.success) {
        deptData.value = res.data
        if (!init) {
          allDeptData.value = deepClone(res.data)
        }
        init = true
        maxLevel.value = res.data[0].level
        parentDeptData.value = convertChildrenToEmptyArray(deepClone(res.data))
        // total.value = deptData.value.length;
        total.value = res.data.reduce((previousValue, currentValue) => {
          return previousValue + countParentsAndChildren(currentValue)
        }, 0)
        tableData.value = deptData.value.map((val) => {
          const item = {
            pkid: val.pkid,
            areaCode: val.areaCode,
            areaName: val.areaName,
            updateTime: val.updateTime,
            parentName: '',
            parentCode: val.parentCode,
            level: val.level,
            longitude: val.longitude,
            latitude: val.latitude,
            hasChildren: false,
            children: [],
            status: val.status,
          }
          if (val.children && val.children.length) {
            item.hasChildren = true
          }
          return item
        })
      } else {
        ElMessage.error(res.message || '无匹配结果')
      }
    })
    .catch(() => {
      tableShow.value = false
    })
}

onMounted(() => {
  getDeptList()
})

const onSubmit = () => {
  formInline.pageIndex = 1
  getDeptList()
}

const resetField = () => {
  formInline.pageIndex = 1
  formInline.pageSize = 11
  formInline.deptName = ''
  // getRoleList()
  getDeptList()
}

const handleEditClick = (item: DivisionData) => {
  Object.assign(deptInfo, item)
  dialogVisible.value = true
}

const handleDeleteClick = (item: DivisionData) => {
  if (item.pkid === item.areaCode) {
    ElMessage.error('默认导入的部门不能删除！')
    return
  }
  deleteDept(item.areaCode)
    .then((res) => {
      if (res.success) {
        onSubmit()
        ElMessage.success('删除区域成功！')
      } else {
        ElMessage.error(res.message || '删除区域失败！')
      }
    })
    .catch((e) => {
      ElMessage.error(e)
    })
}

const handleAddDept = () => {
  dialogVisible.value = true
}

const user = JSON.parse(localStorage.getItem('user')).user

const getUserId = () => {
  const level = user.roleId
  const id = user.refId
  let result = {}
  switch (level) {
    case 'citymanager':
      result = {}
      break
    case 'checkmanager':
      result = {
        regionId: id,
      }
      break
    case 'streetmanager':
      result = {
        streetId: id,
      }
      break
    case 'socialmanager':
      result = {
        communityId: id,
      }
      break
  }
  return result
}

const exportLoading = ref(false)
const handleExport = () => {
  exportLoading.value = true
  const params = getUserId()
  deptExport(params)
    .then((res) => {
      downloadFileWithBlob(res, '行政区划信息.xlsx')
    })
    .catch((err) => {
      ElMessage.error('下载失败')
    })
    .finally(() => {
      exportLoading.value = false
    })
}

const handleDialogClose = () => {
  dialogVisible.value = false
  Object.assign(deptInfo, {
    areaCode: '',
    areaName: '',
    level: -1,
    parentCode: '',
    pkid: '',
    children: null,
    longitude: null,
    latitude: null,
  })
}

const handleDeptUpdate = () => {
  dialogVisible.value = false
  onSubmit()
}

// const getTextByStatus = (status: 1 | 2) => {
//   if (status === 1) {
//     return "禁用";
//   } else {
//     return "启用";
//   }
// };

// const confirmEvent = (pkid: string, status: 1 | 2) => {
//   let params;
//   if (status === 1) {
//     params = {
//       roleState: 2,
//     };
//   } else {
//     params = {
//       roleState: 1,
//     };
//   }
//   // updateUser(pkid, params).then(res => {
//   //   if (res.success) {
//   //
//   //     this.$message.success('更新角色成功！')
//   //   }
//   // })
// };
</script>

<style lang="scss" scoped>
.base-map-resource-content {
  width: 100%;
  height: calc(100% - 27px);
  background-color: white;
  box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);
  border-radius: 2px;

  .query-content {
    padding-left: 20px;
    width: 100%;
    height: 80px;
    line-height: 80px;
    border-bottom: 1px solid #eeeff5;

    :deep(.el-form) {
      height: 80px;
      //margin-bottom: 20px;
      .el-form-item {
        margin-bottom: 0;

        .resetButton {
          width: 80px;
          height: 32px;
          color: #28b1e4;
          background: #ffffff;
          border: 1px solid #28b1e4;
          border-radius: 2px;
        }

        .queryButton {
          width: 80px;
          height: 32px;
          background: #28b1e4;
          border-radius: 2px;
        }
      }
    }
  }

  .addButton {
    margin-left: 20px;
    margin-top: 14px;
    margin-bottom: 14px;
    width: 100px;
    height: 32px !important;
    min-height: 32px;
    //background: #28b1e4;
    border-radius: 2px;
    //border: none;
    padding: 0;
  }

  .table-content {
    display: flex;
    flex-direction: column;

    width: 100%;
    height: calc(100% - 63px);

    .table {
      width: 100%;
      flex: 1;
      padding: 0 18px;
      //height: calc(100% - 77px - 32px - 28px);
      overflow: hidden;

      :deep(.el-table) {
        //max-height: 582px;
        overflow-y: auto;

        .el-table__cell {
          .cell {
            padding-left: 75px;
          }
        }

        .el-header--level-5 {
          padding-left: 130px;
        }

        .el-header--level-1 {
          padding-left: 124px;
        }

        .el-header--level-2 {
          padding-left: 130px;
        }

        .el-header--level-3 {
          padding-left: 135px;
        }

        .el-header--level-5 {
          .el-table__indent {
            padding-left: 150px !important;
          }
        }

        .el-header--level-special {
          padding-left: 146px;
        }

        .el-table__row--level-1 {
          .el-table__indent {
            padding-left: 180px !important;
          }
        }
        .el-table__row--level-2 {
          .el-table__indent {
            padding-left: 360px !important;
          }
        }
        .el-table__row--level-3 {
          .el-table__indent {
            padding-left: 540px !important;
          }
        }

        .el-table__row--level-4 {
          .el-table__indent {
            padding-left: 720px !important;
          }
        }
      }

      .userName {
        .item {
          margin-left: 6px;
        }
        :deep(.el-icon) {
          vertical-align: sub;

          .svg-icon {
            svg {
              width: 16px;
              height: 16px;
              color: #28b1e4;
            }
          }
        }
        :deep(.el-badge__content) {
          width: 12px;
          height: 13px;
          transform: translateY(85%) translateX(148%);
        }
      }

      :deep(.el-table__row--striped) {
        background: #f7f9fb;
      }
    }

    .el-pagination {
      margin: 15px 18px 40px 0;
      justify-content: end;
      padding-right: 80px;
    }
  }
}
</style>
